package com.purang.web.exception;

import com.purang.web.common.CommonResponseCode;
import com.purang.web.entity.vo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 统一异常处理
 *
 * @author Zheming Liu
 * @version 1.0-RELEASE
 * @since 1.0-RELEASE
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandle {

    /**
     * 执行异常
     */
    @ExceptionHandler
    public ResponseVo executeExceptionHandle(Exception e) {
        log.error(e.getMessage(), e);
        return ResponseVo.fail();
    }

    /**
     * 业务异常
     */
    @ExceptionHandler
    public ResponseVo businessExceptionHandle(BusinessException e) {
        log.error(e.getMessage(), e);
        return ResponseVo.fail(e);
    }

    /**
     * 方法不允许异常
     */
    @ExceptionHandler
    public ResponseVo handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e) {
        log.error(e.getMessage(), e);
        return ResponseVo.fail(CommonResponseCode.REQUEST_METHOD_ERROR);
    }

    /**
     * 参数校验异常
     */
    @ExceptionHandler
    public ResponseVo exceptionHandler(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        return ResponseVo.fail(CommonResponseCode.SERVER_ERROR.getCode(), e.getBindingResult().getAllErrors().get(0) == null ? e.getMessage() : e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

    /**
     * 参数校验异常
     */
    @ExceptionHandler(BindException.class)
    public ResponseVo exceptionHandler(BindException e) {
        log.error(e.getMessage(), e);
        return ResponseVo.fail(CommonResponseCode.SERVER_ERROR.getCode(), e.getAllErrors().get(0) == null ? e.getMessage() : e.getAllErrors().get(0).getDefaultMessage());
    }
}
